
#include "UdpClient.h"
#include "../../common/ErrorCode.h"
#include "../../common/ComUtils.h"
#include "../../common/EvURI.h"
#include <event2/util.h>


std::error_code UdpClient::dial(const std::string& uriStr)
{
    EvURI uri;
    auto ec = uri.parse_from_string(uriStr);
    if (ec) {
        return ec;
    }
    sockaddr_storage remote = {};
    ec = uri_dns_resolve(uri, remote);
    if (ec) {
        return ec;
    }

    ez_socket_t fd = ::socket(remote.ss_family, SOCK_DGRAM, 0);
    if (fd < 0) {
        return make_socket_error_code(EVUTIL_SOCKET_ERROR());
    }

    if (::connect(fd, (struct sockaddr*)&remote, sizeof(remote))) {
        evutil_closesocket(fd);
        return make_socket_error_code(EVUTIL_SOCKET_ERROR());
    }
    if (evutil_make_socket_nonblocking(fd) < 0) {
        evutil_closesocket(fd);
        return make_socket_error_code(EVUTIL_SOCKET_ERROR());
    }

    socklen_t len = sizeof(local_point_);
    getsockname(fd, (sockaddr*)&local_point_, &len);
    conn_ = std::make_shared<UdpTmpConn>(remote, local_point_, loop_, fd, true);
    
    return attach(fd);
}
